package org.jgs1904.chanmufeng;

/**
 * 简单的懒汉式单例
 * 在线程1还没有完成实例化之前，线程2已经完成实例化并返回了
 *
 * @author: 默苍璃
 * @date: 2024-07-01 10:02
 */
public class LazySimpleSingleton3 {

    private static LazySimpleSingleton3 instance;

    private LazySimpleSingleton3() {
    }

    public static LazySimpleSingleton3 getInstance() {
        if (instance == null) {
            synchronized (LazySimpleSingleton3.class) {
                if (instance == null) {
                    instance = new LazySimpleSingleton3();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            LazySimpleSingleton3 singleton = LazySimpleSingleton3.getInstance();
            try {
                Thread.sleep(1000); // 模拟线程1执行过程
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread 1: " + System.identityHashCode(singleton));
        });

        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(500); // 线程2稍早启动，但执行的时间短
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LazySimpleSingleton3 singleton = LazySimpleSingleton3.getInstance();
            System.out.println("Thread 2: " + System.identityHashCode(singleton));
        });

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();
    }

}